<template>
  <div class="doctor-activities">
    <el-container>
      <el-header class="activity-header">
        <div class="header-content">
          <h2>活动管理</h2>
          <div class="stats-info">
            <el-row :gutter="20">
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-value">{{ attendedCount }}</div>
                  <div class="stat-label">参加活动数</div>
                </div>
              </el-col>
              <el-col :span="8">
                <div class="stat-item">
                  <div class="stat-value">{{ totalPoints }}</div>
                  <div class="stat-label">总积分</div>
                </div>
              </el-col>
              <el-col :span="8">
                <el-button type="primary" @click="refreshData">刷新数据</el-button>
              </el-col>
            </el-row>
          </div>
        </div>
      </el-header>
      
      <el-main class="activity-main">
        <el-tabs v-model="activeTab" @tab-click="handleTabClick">
          <!-- 可报名活动 -->
          <el-tab-pane label="可报名活动" name="available">
            <div class="activity-section">
              <div class="section-header">
                <h3>可报名的活动</h3>
                <el-button @click="loadAvailableActivities">刷新列表</el-button>
              </div>
              
              <el-table 
                :data="availableActivities" 
                v-loading="availableLoading"
                stripe
                style="width: 100%"
              >
                <el-table-column prop="name" label="活动名称" min-width="150" />
                <el-table-column prop="location" label="活动地点" min-width="120" />
                <el-table-column prop="startTime" label="开始时间" min-width="150">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.startTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="endTime" label="结束时间" min-width="150">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.endTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="description" label="活动描述" min-width="200" show-overflow-tooltip />
                <el-table-column prop="points" label="活动积分" width="100">
                  <template #default="scope">
                    <span class="points">{{ scope.row.points || 0 }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="封面" width="80">
                  <template #default="scope">
                    <el-image 
                      v-if="scope.row.cover"
                      :src="scope.row.cover"
                      :preview-src-list="[scope.row.cover]"
                      fit="cover"
                      style="width: 50px; height: 50px; border-radius: 4px;"
                    />
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button 
                      type="primary" 
                      size="small" 
                      @click="showRegisterDialog(scope.row)"
                    >
                      报名
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <el-pagination
                v-if="availableTotal > 0"
                v-model:current-page="availableCurrentPage"
                v-model:page-size="availablePageSize"
                :total="availableTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleAvailableSizeChange"
                @current-change="handleAvailableCurrentChange"
                style="margin-top: 20px; text-align: right;"
              />
            </div>
          </el-tab-pane>
          
          <!-- 已报名活动 -->
          <el-tab-pane label="已报名活动" name="registered">
            <div class="activity-section">
              <div class="section-header">
                <h3>已报名的活动</h3>
                <el-button @click="loadRegisteredActivities">刷新列表</el-button>
              </div>
              
              <el-table 
                :data="registeredActivities" 
                v-loading="registeredLoading"
                stripe
                style="width: 100%"
              >
                <el-table-column prop="name" label="活动名称" min-width="150" />
                <el-table-column prop="location" label="活动地点" min-width="120" />
                <el-table-column prop="startTime" label="开始时间" min-width="150">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.startTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="registrationStatus" label="状态" width="100">
                  <template #default="scope">
                    <el-tag 
                      :type="getStatusType(scope.row.registrationStatus)"
                      size="small"
                    >
                      {{ getStatusText(scope.row.registrationStatus) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="registrationTime" label="报名时间" min-width="150">
                  <template #default="scope">
                    {{ formatDateTime(scope.row.registrationTime) }}
                  </template>
                </el-table-column>
                <el-table-column prop="pointsEarned" label="获得积分" width="100">
                  <template #default="scope">
                    <span class="points">{{ scope.row.pointsEarned || 0 }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" fixed="right">
                  <template #default="scope">
                    <el-button 
                      v-if="scope.row.registrationStatus === 'REGISTERED'"
                      type="danger" 
                      size="small" 
                      @click="cancelRegistration(scope.row)"
                    >
                      取消报名
                    </el-button>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
              </el-table>
              
              <el-pagination
                v-if="registeredTotal > 0"
                v-model:current-page="registeredCurrentPage"
                v-model:page-size="registeredPageSize"
                :total="registeredTotal"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleRegisteredSizeChange"
                @current-change="handleRegisteredCurrentChange"
                style="margin-top: 20px; text-align: right;"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-main>
    </el-container>
    
    <!-- 报名对话框 -->
    <el-dialog 
      v-model="registerDialogVisible" 
      title="活动报名" 
      width="500px"
    >
      <el-form :model="registerForm" :rules="registerRules" ref="registerFormRef">
        <div class="activity-info">
          <h4>{{ selectedActivity?.name }}</h4>
          <p><strong>地点：</strong>{{ selectedActivity?.location }}</p>
          <p><strong>时间：</strong>{{ formatDateTime(selectedActivity?.startTime) }} - {{ formatDateTime(selectedActivity?.endTime) }}</p>
          <p><strong>活动积分：</strong><span class="points">{{ selectedActivity?.points || 0 }} 分</span></p>
          <p><strong>描述：</strong>{{ selectedActivity?.description }}</p>
        </div>
        
        <el-form-item label="备注信息" prop="remark">
          <el-input 
            v-model="registerForm.remark" 
            type="textarea" 
            :rows="4" 
            placeholder="请输入报名备注（可选）"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="registerDialogVisible = false">取消</el-button>
          <el-button 
            type="primary" 
            @click="confirmRegister"
            :loading="registerLoading"
          >
            确认报名
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getAvailableActivities, 
  getRegisteredActivities, 
  registerActivity, 
  cancelActivityRegistration,
  getAttendedActivitiesCount,
  getTotalPoints
} from '@/api/doctor'

export default {
  name: 'DoctorActivities',
  setup() {
    const activeTab = ref('available')
    
    // 统计数据
    const attendedCount = ref(0)
    const totalPoints = ref(0)
    
    // 可报名活动
    const availableActivities = ref([])
    const availableLoading = ref(false)
    const availableCurrentPage = ref(1)
    const availablePageSize = ref(10)
    const availableTotal = ref(0)
    
    // 已报名活动
    const registeredActivities = ref([])
    const registeredLoading = ref(false)
    const registeredCurrentPage = ref(1)
    const registeredPageSize = ref(10)
    const registeredTotal = ref(0)
    
    // 报名对话框
    const registerDialogVisible = ref(false)
    const registerLoading = ref(false)
    const selectedActivity = ref(null)
    const registerFormRef = ref(null)
    
    const registerForm = reactive({
      remark: ''
    })
    
    const registerRules = reactive({
      remark: [
        { max: 200, message: '备注信息不能超过200个字符', trigger: 'blur' }
      ]
    })
    
    // 加载统计数据
    const loadStats = async () => {
      try {
        const [countRes, pointsRes] = await Promise.all([
          getAttendedActivitiesCount(),
          getTotalPoints()
        ])
        
        attendedCount.value = countRes.data || 0
        totalPoints.value = pointsRes.data || 0
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    }
    
    // 加载可报名活动
    const loadAvailableActivities = async () => {
      availableLoading.value = true
      try {
        const params = {
          current: availableCurrentPage.value,
          size: availablePageSize.value
        }
        
        const response = await getAvailableActivities(params)
        
        if (response.code === 200) {
          availableActivities.value = response.data.records || []
          availableTotal.value = response.data.total || 0
        } else {
          ElMessage.error(response.message || '获取可报名活动失败')
        }
      } catch (error) {
        console.error('获取可报名活动失败:', error)
        ElMessage.error('获取可报名活动失败')
      } finally {
        availableLoading.value = false
      }
    }
    
    // 加载已报名活动
    const loadRegisteredActivities = async () => {
      registeredLoading.value = true
      try {
        const params = {
          current: registeredCurrentPage.value,
          size: registeredPageSize.value
        }
        
        const response = await getRegisteredActivities(params)
        
        if (response.code === 200) {
          registeredActivities.value = response.data.records || []
          registeredTotal.value = response.data.total || 0
        } else {
          ElMessage.error(response.message || '获取已报名活动失败')
        }
      } catch (error) {
        console.error('获取已报名活动失败:', error)
        ElMessage.error('获取已报名活动失败')
      } finally {
        registeredLoading.value = false
      }
    }
    
    // 显示报名对话框
    const showRegisterDialog = (activity) => {
      selectedActivity.value = activity
      registerForm.remark = ''
      registerDialogVisible.value = true
    }
    
    // 确认报名
    const confirmRegister = async () => {
      if (!registerFormRef.value) return
      
      await registerFormRef.value.validate(async (valid) => {
        if (!valid) return
        
        registerLoading.value = true
        try {
          const response = await registerActivity(selectedActivity.value.id, {
            remark: registerForm.remark
          })
          
          if (response.code === 200) {
            ElMessage.success('报名成功!')
            registerDialogVisible.value = false
            
            // 刷新数据
            loadAvailableActivities()
            loadRegisteredActivities()
            loadStats()
          } else {
            ElMessage.error(response.message || '报名失败')
          }
        } catch (error) {
          console.error('报名失败:', error)
          ElMessage.error('报名失败')
        } finally {
          registerLoading.value = false
        }
      })
    }
    
    // 取消报名
    const cancelRegistration = async (activity) => {
      try {
        await ElMessageBox.confirm(
          '确定要取消报名这个活动吗？',
          '确认取消',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        const response = await cancelActivityRegistration(activity.id)
        
        if (response.code === 200) {
          ElMessage.success('取消报名成功!')
          
          // 刷新数据
          loadAvailableActivities()
          loadRegisteredActivities()
          loadStats()
        } else {
          ElMessage.error(response.message || '取消报名失败')
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('取消报名失败:', error)
          ElMessage.error('取消报名失败')
        }
      }
    }
    
    // 刷新所有数据
    const refreshData = () => {
      loadStats()
      if (activeTab.value === 'available') {
        loadAvailableActivities()
      } else {
        loadRegisteredActivities()
      }
    }
    
    // 标签页切换
    const handleTabClick = (tab) => {
      if (tab.name === 'available') {
        loadAvailableActivities()
      } else {
        loadRegisteredActivities()
      }
    }
    
    // 分页处理
    const handleAvailableSizeChange = (size) => {
      availablePageSize.value = size
      loadAvailableActivities()
    }
    
    const handleAvailableCurrentChange = (page) => {
      availableCurrentPage.value = page
      loadAvailableActivities()
    }
    
    const handleRegisteredSizeChange = (size) => {
      registeredPageSize.value = size
      loadRegisteredActivities()
    }
    
    const handleRegisteredCurrentChange = (page) => {
      registeredCurrentPage.value = page
      loadRegisteredActivities()
    }
    
    // 格式化日期时间
    const formatDateTime = (dateTime) => {
      if (!dateTime) return '-'
      const date = new Date(dateTime)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      })
    }
    
    // 获取状态类型
    const getStatusType = (status) => {
      const statusMap = {
        'REGISTERED': 'info',
        'ATTENDED': 'warning',
        'COMPLETED': 'success',
        'CANCELLED': 'danger'
      }
      return statusMap[status] || 'info'
    }
    
    // 获取状态文本
    const getStatusText = (status) => {
      const statusMap = {
        'REGISTERED': '已报名',
        'ATTENDED': '已参加',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }
    
    onMounted(() => {
      loadStats()
      loadAvailableActivities()
    })
    
    return {
      activeTab,
      attendedCount,
      totalPoints,
      availableActivities,
      availableLoading,
      availableCurrentPage,
      availablePageSize,
      availableTotal,
      registeredActivities,
      registeredLoading,
      registeredCurrentPage,
      registeredPageSize,
      registeredTotal,
      registerDialogVisible,
      registerLoading,
      selectedActivity,
      registerFormRef,
      registerForm,
      registerRules,
      loadAvailableActivities,
      loadRegisteredActivities,
      showRegisterDialog,
      confirmRegister,
      cancelRegistration,
      refreshData,
      handleTabClick,
      handleAvailableSizeChange,
      handleAvailableCurrentChange,
      handleRegisteredSizeChange,
      handleRegisteredCurrentChange,
      formatDateTime,
      getStatusType,
      getStatusText
    }
  }
}
</script>

<style scoped>
.doctor-activities {
  height: 100vh;
  background-color: #f5f5f5;
}

.activity-header {
  background: white;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  padding: 0;
}

.header-content {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content h2 {
  margin: 0;
  color: #303133;
}

.stats-info {
  min-width: 400px;
}

.stat-item {
  text-align: center;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 5px;
}

.stat-label {
  color: #666;
  font-size: 12px;
}

.activity-main {
  padding: 20px;
}

.activity-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #303133;
}

.activity-info {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  margin-bottom: 20px;
}

.activity-info h4 {
  margin: 0 0 10px 0;
  color: #409eff;
}

.activity-info p {
  margin: 5px 0;
  color: #606266;
}

.points {
  color: #f56c6c;
  font-weight: bold;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-tabs__content) {
  padding: 0;
}

:deep(.el-table .cell) {
  word-break: break-word;
}
</style>
